<?
require_once("pg_mon/class_HostCluster.php");

class WUHostCluster extends HostCluster {

    public function WHHostCluster($hc_id=false) {
	parent::__construct($hc_id);
    }

// *************************************************************************************************
    public function discover() {
	if (!$this->prod_sql) {
	    $this->prod_sql=new SQL($this->get_conn_string());
	}
	$this->prod_sql->select_c("SELECT current_setting('server_version') AS ver");
	$sv=$this->prod_sql->get_row_hash();

        if ($this->get_field('pg_version') != $sv['ver']) {
	    $this->set_field('pg_version',$sv['ver']);
	    $this->save();
	}

	$this->prod_sql->select_c("SELECT current_setting('data_directory') AS pg_data_path");
	$dp=$this->prod_sql->get_row_hash();

        if ($this->get_field('pg_data_path') != $dp['pg_data_path']) {
	    $this->set_field('pg_data_path',$dp['pg_data_path']);
	    $this->save();
	}
	$this->prod_sql->select_c("SELECT CASE WHEN current_setting('track_counts')='on' THEN 't'::boolean ELSE 'f'::boolean END AS track_counts");
	$tc=$this->prod_sql->get_row_hash();
	if ($this->get_field('track_counts') != $tc['track_counts']) {
	    $this->set_field('track_counts',$tc['track_counts']);
	    $this->save();
	}

	if ($this->pg_version2int($this->get_field('pg_version')) >= FUNCTION_STAT_MIN_VERSION) {
	    $this->prod_sql->select_c("SELECT current_setting('track_functions') AS track_functions");
	    $tf=$this->prod_sql->get_row_hash();
	    if ($this->get_field('track_functions') != $tf['track_functions']) {
		$this->set_field('track_functions',$tf['track_functions']);
		$this->save();
	    }
	}

	$this->prod_sql->select_c("SELECT oid,datname FROM pg_database WHERE NOT datistemplate AND datname !='postgres'");

	$this->initiate_composit('database_name',array('alive'=>'t'));
	$exist_ids=$this->get_composit('database_name',COLLECTION_ID_ARRAY);

	foreach ($this->prod_sql->get_result() as $prod_db) {
	    $exist_id=$this->composit_obj_exists('database_name','obj_oid',$prod_db['oid']);
	    if (!$exist_id) {
		$dn=new DatabaseName;
		$dn->set_field('db_name',$prod_db['datname']);
		$dn->set_field($this->composit_array['database_name']['link_fk'],$this->id);
		$dn->set_field('obj_oid',$prod_db['oid']);
		$dn->set_field('observable','f');
		$dn->save();
		$this->add_composit_object('schema_name',$dn->get_id());
	    } else {
		foreach ($exist_ids as $id=>$val) {
		    if ($val == $exist_id) {
			unset($exist_ids[$id]);
		    }
		}
	    }
	}
	foreach ($exist_ids as $old_id) {
	    $old_dn=new DatabaseName($old_id);
	    $old_dn->set_field('alive','f');
	    $old_dn->save();
	    $this->remove_composit_object('database_name',$old_id);

	}
    }

// *************************************************************************************************

    public function update_cluster($changes) {
	$old=$this->get_all_fields();
	if ($old['hostname'] != $changes['edit_cluster_hostname']) {
	    $this->set_field('hostname',$changes['edit_cluster_hostname']);
	}
	if ($old['ip_address'] != $changes['edit_cluster_ip_address']) {
	    $this->set_field('ip_address',$changes['edit_cluster_ip_address']);
	}
	if ($old['is_master'] != $changes['edit_cluster_is_master']) {
	    $this->set_field('is_master',$changes['edit_cluster_is_master']);
	}

	if (isset($changes['edit_cluster_fqdn']) && $old['fqdn'] != $changes['edit_cluster_fqdn']) {
	    $this->set_field('fqdn',$changes['edit_cluster_fqdn']);
	}
	if (isset($changes['edit_cluster_spec_comments']) && $old['spec_comments'] != $changes['edit_cluster_spec_comments']) {
	    $this->set_field('spec_comments',$changes['edit_cluster_spec_comments']);
	}

/************/
	$conn_param="{";
	$conn_param.="hostaddr=".$changes['edit_cluster_ip_address'].",";
	$conn_param.="dbname=".$changes['edit_cluster_conn_dbname'].",";
	$conn_param.="port=".$changes['edit_cluster_conn_port'].",";
	$conn_param.="user=".$changes['edit_cluster_conn_user'].",";
	if ($changes['edit_cluster_conn_password']) {
	    $conn_param.="password=".$changes['edit_cluster_conn_password'].'",';
	}
	$conn_param.="sslmode=".$changes['edit_cluster_conn_sslmode']."}";
	if ($old['conn_param'] != $conn_param) {
	    $this->set_field('conn_param',$conn_param);
	}
	$this->save();
    }

// *************************************************************************************************

    public static function cluster_add_edit_form($id=false) {
    $prefix='add';
    if ($id) {
        $prefix='edit';
        $hc=new HostCluster($id);
    }
    $string="<form method=POST action=".$_SERVER['PHP_SELF'].">";

    if ($id) {
        $string.= "<input type=hidden name=".$prefix."_cluster_id value=".$id.">
		<input type=hidden name=id value=".$id.">
	    <input type=hidden name=level value=cluster>";
    } else {
	$string.="<input type=hidden name=level value=init>";
    }
    $string.="

<table border=0 align=center width=70%>
    <tr align=center valign=top>
        <td align=left>";
    if ($id) {
	$string.="
<a href=".$_SERVER['PHP_SELF']."?level=cluster&action=discover&id=".$id.">Discover</a><br>";
    } else {
	$string.="Discover";
    }
	$string.="
</td><td>

PostgreSQL Host Info<br><br>
<table border=0 align=center>
    <tr>
        <td>Host Name</td>
        <td><input type=text name=".$prefix."_cluster_hostname required".($id ? " value=".$hc->get_field('hostname') : ' placeholder=required')."></td>
    </tr><tr>
        <td>IP Address</td>
        <td><input type=text name=".$prefix."_cluster_ip_address required".($id ? " value=".$hc->get_field('ip_address') : ' placeholder=required')."></td>
    </tr><tr>
        <td>F.Q.D.N.</td>
        <td><input type=text name=".$prefix."_cluster_fqdn".(($id && $hc->get_field('fqdn')) ? " value=\"".$hc->get_field('fqdn').'"' : '')."></td>
    </tr><tr>
        <td>Db Role</td>
        <td><select name=".$prefix."_cluster_is_master>";

    $option_string="";
    foreach (array("Slave"=>'f',"Master"=>'t') as $name=>$val) {
        $option_string.="<option";
        if ($id) {
            if ($hc->get_field('is_master')==$val) {
                $option_string.=" selected";
            }
        } else {
            if ($val=='t') {
                $option_string.=" selected";
            }
        }
        $option_string.=" value=$val>$name";
    }
    $string.=$option_string;

    $string.="
        </select>
        </td>
    </tr><tr valign=top>
        <td>Comments</td>
        <td><textarea name=".$prefix."_cluster_spec_comments rows=7 cols=45>".(($id && $hc->get_field('spec_comments')) ? $hc->get_field('spec_comments') : '')."</textarea></td>
    </tr>

</table>";

    if ($id) {
        $params=array();
        foreach (preg_split('/ /',$hc->get_conn_string()) as $param) {
            list($p,$v)=preg_split('/=/',$param);
            $params[$p]=$v;
        }
    }
    $string.="

        </td><td>

Connection parameters (<b>libpq</b> library)<br><br>
<table border=0 align=center>
    <tr>
        <td>port</td>
        <td><input type=text name=".$prefix."_cluster_conn_port value=".($id ? $params['port'] : '5432')."></td>
    </tr><tr>
        <td>dbname</td>
        <td><input type=text name=".$prefix."_cluster_conn_dbname value=".($id ? $params['dbname'] : 'postgres')."></td>
    </tr><tr>
        <td>user</td>
        <td><input type=text name=".$prefix."_cluster_conn_user value=".($id ? $params['user'] : 'postgres')."></td>
    </tr><tr>
        <td>password</td>
        <td><input type=password name=".$prefix."_cluster_conn_password value=".($id && isset($params['password']) ? $params['password'] : '').">
        </td>
    </tr><tr>
        <td>sslmode</td>
        <td align=center><select name=".$prefix."_cluster_conn_sslmode>";

    $opt_string='';
    $sslmode=array('disable','allow','prefer','require','verify-ca','verify-full');
    foreach ($sslmode as $mode) {
        if ($id) {
            if ($mode == $params['sslmode']) {
                $opt_string.="<option selected>".$mode;
            } else {
                $opt_string.="<option>".$mode;
            }
        } else {
            if ($mode == 'prefer') {
                $opt_string.="<option selected>".$mode;
            } else {
                $opt_string.="<option>".$mode;
            }
        }
    }
    $string.=$opt_string;
    $string.="
        </select>
        </td>
    </tr>
</table>

        </td>
    </tr>
</table>
<center>";

    if ($id) {
	$string.= "libpq Connection string<br><b>".$hc->get_conn_string(true)."</b>";
    }

    $string.="

</center>

<br>
<hr width=70%>
<br>
<center><input type=submit name=".$prefix."_cluster_submit value=Submit></center>
</form>";
    return $string;
}


// *************************************************************************************************
    public function get_view() {
    $string="

<table border=0 align=center width=70%>
    <tr align=center valign=top>
        <td align=left>";
	if ($this->get_field('is_master')=='t') {
	    $string.="<a href=".$_SERVER['PHP_SELF']."?level=cluster&action=discover&id=".$this->id.">Discover</a><br>";
	} else {
	    $string.="Discover<br>";
	}
	$string.="<a href=".$_SERVER['PHP_SELF']."?level=cluster&action=edit&id=".$this->id.">Edit</a><br>

</td><td>

PostgreSQL Host Info<br><br>
<table border=0 align=center>
    <tr>
        <td>Host Name</td>
        <td><b>".$this->get_field('hostname')."</b></td>
    </tr><tr>
        <td>IP Address</td>
        <td><b>".$this->get_field('ip_address')."</b></td>
    </tr><tr>
        <td>F.Q.D.N.</td>
        <td><b>".($this->get_field('fqdn') ? $this->get_field('fqdn') : '')."</b></td>
    </tr><tr bgcolor=#DDD>
	<td>PG Version</td>
	<td>".($this->get_field('pg_version') ? '<b>'.$this->get_field('pg_version').'</b>' : '<i>Not discovered</i>')."</td>
    </tr><tr bgcolor=#DDD>
	<td>PG Data Path</td>
	<td>".($this->get_field('pg_data_path') ? '<b>'.$this->get_field('pg_data_path').'</b>' : '<i>Not discovered</i>')."</td>
    </tr><tr bgcolor=#DDD>
	<td>Track Counters</td>
	<td>".($this->get_field('track_counts') ? ($this->get_field('track_counts')=='t' ? '<b>Enabled</b>' : '<b>Disabled</b>') : '<i>Not discovered</i>')."</td>
    </tr><tr bgcolor=#DDD>
	<td>Track functions</td>
	<td>".($this->get_field('track_functions') ? '<b>'.$this->get_field('track_functions').'</b>' : '<i>Not discovered</i>')."</td>
    </tr><tr>


        <td>Db Role</td>
        <td><b>".($this->get_field('is_master')=='t' ? 'Master' : 'StandBy')."</b></td>
    </tr><tr valign=top>
        <td>Comments</td>
        <td><textarea readonly wrap disabled rows=7 cols=45>".($this->get_field('spec_comments') ? $this->get_field('spec_comments') : '')."</textarea></td>
    </tr>

</table>";


    $params=array();
    foreach (preg_split('/ /',$this->get_conn_string()) as $param) {
	list($p,$v)=preg_split('/=/',$param);
	$params[$p]=$v;
    }
    $string.="

        </td><td>

Connection parameters (<b>libpq</b> library)<br><br>
<table border=0 align=center>
    <tr>
        <td>port</td>
        <td>".$params['port']."</td>
    </tr><tr>
        <td>dbname</td>
        <td>".$params['dbname']."</td>
    </tr><tr>
        <td>user</td>
        <td>".$params['user']."</td>
    </tr><tr>
        <td>password</td>
        <td>*******</td>
    </tr><tr>
        <td>sslmode</td>
        <td align=center>".$params['sslmode']."</td>
    </tr>
</table>

        </td>
    </tr>
</table>
<center>";

	$string.= "libpq Connection string<br><b>".$this->get_conn_string(true)."</b>";

    $string.="

</center>

<br>
<hr width=70%>
<br>";
	return $string;
    }


// *************************************************************************************************

    public function __toString() {
	return $this->get_field('hostname');
    }
}

?>
